const {
	toUrl,
	globalData
} = getApp()
import {
	request
} from '@/utils/request'
Page({
	toUrl,
	data: {
		globalData,
		current: 0,
		goodsId: '',
		detail: null,
		type: 1,
		headbc: '',
		act: '/img/act3.png',
		shareShow: false,
		poster: null
	},
	shows: function () {
		// wx.showToast({
		//     title: '生成海报中...',
		//     icon:"loading",
		//     mask:true,
		// })
		this.setData({
			shareShow: true
		})
		this.drawPoster()

	},

	//收藏
	handleCollesd() {
		const that = this
		const data = {
			goods_id: that.data.goodsId,
			typeid: that.data.detail.is_collect == 0 ? 1 : 2
		}
		request('stores/goodscollect', {
			show: true,
			data
		}).then(res => {
			that.getDetail()
		})
	},
	handleShare() {
		// console.log(this.data.detail.images.length);
		if (this.data.detail.images.length == 0) {
			wx.showToast({
				title: '未上传商品图，请上传',
				icon: 'none'
			})
			return
		}
		this.shows()
	},
	drawPoster() {
		const query = wx.createSelectorQuery()
		const self = this;
		//...判断本地信息，引导用户授权获取头像部分

		query.select('#myCanvas')
			.fields({
				node: true,
				size: true
			})
			.exec(async (res) => {
				self.canvas = res[0].node
				self.ctx = self.canvas.getContext('2d')
				//屏幕像素比
				const dpr = wx.getSystemInfoSync().pixelRatio
				self.canvas.width = res[0].width * dpr
				self.canvas.height = res[0].height * dpr
				//画布放大后绘制比例也相应放大，这样绘图时就能按原尺寸计算
				self.ctx.scale(dpr, dpr)
				//...画布适配部分
				//背景
				self.ctx.fillStyle = '#fff'
				self.ctx.fillRect(0, 0, self.canvas.width, self.canvas.height)
				// self.ctx.fillStyle='pink'
				// self.ctx.fillRect(0, 0, 300, 300)
				//...背景及文字绘制部分
				//文字
				self.ctx.textBaseline = 'top'
				self.ctx.textAlign = 'left'
				self.ctx.fillStyle = '#000'
				self.ctx.font = '16px  Helvertica'
				self.ctx.fillText("分享你一个好物", 10, 15)
				wx.showLoading({
					title: '海报生成中'
				});
				//获取头像和二维码和背景图
				//  self.getBgImg()
				const result = await Promise.all([self.getQrcode(), self.getBgImg()]).catch((err) => {
					console.log(err);
				})

				console.log(result);
				if (result == undefined) {
					wx.showToast({
						title: '未上传主图图片',
						icon: 'none'
					})
					// wx.hideLoading()
					setTimeout(() => {
						self.setData({
							shareShow: false
						})
					}, 1500);

				}
				await Promise.all([self.drawQRcode2(result[0]), self.drawBgImg(result[1]), self.drawTitle()])

				wx.hideLoading()
				//将canvas转化成临时路径，用imge加载生成图片呈现在页面
				self.canvas2Img()
			})
	},

	canvas2Img() {
		const self = this
		console.log(55555);
		setTimeout(() => {
			//将画布保存成临时路径 供展示
			wx.canvasToTempFilePath({
				//因为是2d所以需要传入整个canvas节点
				canvas: self.canvas,
				success: (res) => {
					//将路径保存下来通过image在页面上展示
					console.log(res);
					this.setData({
						poster: res.tempFilePath
					})
					//   self.poster = 
				},
				fail: (res) => {
					console.log(`fail`, res)
				}
			}, self)
		}, 200)
	},
	//获取小程序二维码
	getQrcode() {
		console.log(11122888);
		return new Promise((resolve, reject) => {
			let errorData = {
				code: 0,
				msg: '请求失败: 1.未上传主图图片;2.二维码绘制失败'
			}
			let successData = {
				code: 1,
				msg: '请求成功'
			}

			let pages = getCurrentPages() //获取加载的页面
			let currentPage = pages[pages.length - 1] //获取当前页面的对象
			let url = currentPage.route //当前页面url
			let options = currentPage.options //如果要获取url中所带的参数可以查看options
			let urlWithArgs = url + '?'
			for (let key in options) {
				let value = options[key]
				urlWithArgs += key + '=' + value + '&'
			}
			urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

			console.log(urlWithArgs);

			let data = {
				typeid: 2,
				scene: '?id=' + this.data.goodsId
			}
			request('currency/getwxacodeunlimit', {
				data
			}).then(res => {
				console.log(res);

				resolve(res.data.qrcode)

			}).catch((err) => {
				reject(errorData)
			})

		})
	},
	//计算文本超出超短函数
	getTextCt(str) {
		const self = this;
		console.log(self.canvas.width)
		let canvasWidth = self.canvas.width
		let fontSize = parseInt((wx.getSystemInfoSync().windowWidth / 375) * 30)
		let rowFontNum = Math.floor(canvasWidth / fontSize)
		let strLength = str.length
		let rows = Math.ceil(strLength / rowFontNum)
		return {
			canvasWidth,
			fontSize,
			rowFontNum,
			strLength,
			rows
		}
	},
	//绘制商品标题
	drawTitle() {
		const self = this;
		const dpr = wx.getSystemInfoSync().pixelRatio

		let height = self.canvas.height / dpr
		let chazhi = height - 100
		console.log(chazhi);
		// const context = wx.createCanvasContext('myCanvas')
		var text = this.data.detail.goods_name; //这是要绘制的文本
		// var text = '你好你好你好单独你好你好你好单独你好你好你好单独你好你好你好单独'; //这是要绘制的文本
		var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
		var temp = "";
		var row = [];
		let len = 0
		self.ctx.font = 'bold  14px Helvertica'

		self.ctx.fillStyle = '#000'

		for (var a = 0; a < chr.length; a++) {
			if (self.ctx.measureText(temp).width < 170) {
				temp += chr[a];
			} else {
				a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
				row.push(temp);
				temp = "";
			}
		}
		row.push(temp);

		//如果数组长度大于2 则截取前两个
		if (row.length > 2) {
			console.log(99999999);
			var rowCut = row.slice(0, 2);
			var rowPart = rowCut[1];
			var test = "";
			var empty = [];
			for (var a = 0; a < rowPart.length; a++) {
				if (self.ctx.measureText(test).width < 170) {
					test += rowPart[a];
				} else {
					break;
				}
			}
			empty.push(test);
			var group = empty[0] + "..." //这里只显示两行，超出的用...表示
			rowCut.splice(1, 1, group);
			row = rowCut;
		}
		console.log(row);
		if (row.length > 1) {
			len = 0
		} else {
			len = 10

		}
		for (var b = 0; b < row.length; b++) {
			self.ctx.fillText(row[b], 10, chazhi + 25 + b * 30 + len, 170);
		}
	},


	//绘制二维码图像
	drawQRcode2(bufferData) {
		const self = this;
		const dpr = wx.getSystemInfoSync().pixelRatio
		let wid = self.canvas.width / dpr
		let height = self.canvas.height / dpr
		let chazhi = height - 140

		return new Promise((resolve, reject) => {
			let image = self.canvas.createImage();
			//加载buffer数据
			image.src = bufferData;
			image.onload = () => {
				self.ctx.drawImage(image, wid - 90, chazhi + 50, 80, 80);
				resolve()
			}
		})
	},
	//绘制背景图
	drawBgImg(src) {
		const self = this;
		const dpr = wx.getSystemInfoSync().pixelRatio
		const width = self.canvas.width / dpr
		const height = self.canvas.height / dpr
		console.log(width, height);
		return new Promise((resolve, reject) => {
			let image = self.canvas.createImage();
			image.src = src;
			image.onload = (res) => {
				self.ctx.drawImage(image, 0, 40, width, height - 140);
				resolve()
			}

		})
	},
	//获取背景图
	getBgImg() {
		const self = this
		return new Promise((resolve, reject) => {
			let errorData = {
				code: 0,
				msg: '请求失败: 1.未上传主图图片;2.二维码绘制失败'
			}
			let successData = {
				code: 1,
				msg: '请求成功'
			}
			let imglist = self.data.detail.images
			if (imglist.length == 0) {
				// console.log(9999999);
				reject(errorData)
			} else {
				resolve(imglist[0], successData)
			}
			console.log(img1, '------');
			// if (condition) {

			// }
			// resolve
			//获取云存储中的图片
			//   self.getImgInfo('cloud://cloud1-8gp38tt58f1cad0e.636c-cloud1-8gp38tt58f1cad0e-1306912889/mdata/img/weiwuxian2.jpg').then(res=>{
			//     console.log(`cloudImg`,res)
			//     //{errMsg: "getImageInfo:ok", width: 794, height: 794, type: "jpeg", orientation: "up",path: "http://tmp/wsz3Rlfyo5yj279d60b79b9c747d19a192f79e7e9cb8.jpg",type:"jpeg",width:794}
			//     if(res && res.path){
			//       resolve(res.path)
			//     }else{
			//       reject()
			//     }
			//   })
		})
	},

	//处理头部滚动事件
	onPageScroll(e) {
		const scrollTop = e.scrollTop
		if (scrollTop > 150) {
			this.setData({
				headBc: 'headbc',
				act: '/image/icon-arrow-left.png'
			})
		} else {
			this.setData({
				headBc: '',
				act: '/img/act3.png'
			})
		}
	},
	//拨打电话
	makePhoneCall() {
		wx.makePhoneCall({
			phoneNumber: this.data.detail.kefu //仅为示例，并非真实的电话号码
		})
	},
	getTypes(data) {
		console.log(data);
		let {
			type
		} = data.currentTarget.dataset
		this.setData({
			type: type
		})
	},
	changeSwiper({
		detail
	}) {
		const {
			current
		} = detail
		this.setData({
			current
		})
	},
	getDetail() {
		const that = this
		const data = {
			goods_id: this.data.goodsId
		}
		request('user/integralinfo', {
			data
		}).then(res => {
			// const list = res.data


			let contents
            let zhengze = new RegExp('<img', 'g')
                        let zhengze1 = new RegExp('<p', 'g')
            contents = res.data.purchase_notes.replace(zhengze1, '<p style="width:100%;height:auto;display:block;margin:10px 0;" ')
            contents = contents.replace(zhengze, '<img style="width:100%;height:auto;display:block;" ')
            res.data.purchase_notes = contents
	
			that.setData({
				detail: res.data
			})
		})
	},
	// 兑换商品
	getAaddorder() {
		console.log(11);
		let detail1 = this.data.detail
		if (detail1.quota_num != 0) {
			if (detail1.buy_num >= detail1.quota_num) {
				wx.showToast({
					title: `限购数量${detail1.quota_num}`,
					icon: 'none'
				})
				return

			}
		}
		if (detail1.store_count == 0) {
			wx.showToast({
				title: `库存为0`,
				icon: 'none'
			})
			return
		}
		const that = this
		const data = {
			goods_id: this.data.goodsId
		}
		wx.showModal({
			title: "提示",
			content: "是否确认兑换",
			confirmColor: "#286BFB",
			cancelColor: "#666",
			confirmText: "确认兑换",
			success(res) {
				if (res.confirm) {
					wx.showLoading()
					request('integral/addorder', {
						data
					}).then(res => {
						wx.showToast({
							title: '兑换成功'
						})
						that.getDetail()
					})
				}
				
			}
		})



	},
	toTop() {
		wx.pageScrollTo({
			scrollTop: 400,
			duration: 300
		})
	},
	toBottom() {
		wx.pageScrollTo({
			// scrollTop: 10000,
			selector:'.dhxz_box',
            offsetTop: -80,
			duration: 300
		})
	},
	onLoad(options) {

		let id = ''
        if (options.id == undefined) {
            id = decodeURIComponent(options.scene).split('?')[1].split('=')[1]
        }else{
            id = options.id
        }
		this.setData({
			goodsId: id
		})
		this.getDetail()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		console.log('我的积分页面');
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})